package org.biogroovy.conf

import java.nio.file.FileSystems
import java.nio.file.Path


/**
 * BioGroovy makes use of a number of REST services which require user keys.  These user keys
 * are stored in a file called 'biogroovy.conf' found in your ~/.biogroovy directory.  If the
 * keys required by a service are not found in the configuration file, an exception will be thrown.
 *
 */
class BioGroovyConfig {

	private static ConfigObject config = null;

	private static final String msg = '''
		The ~/.biogroovy/biogroovy.conf file was not initialized properly.  
		You must use your own information in order for the RESTful services to work properly.
		A demo version of the config file has been copied to this directory. Please modify
		the file with your own information.
	'''

	/**
	 * This method gets the BioGroovy configuration.  This method looks
	 * for a Config.groovy file located at ${System.getProperty('user.home')}/.biogroovy/biogroovy.conf/
	 * If the file does not exist at this location, then it defaults to the
	 * biogroovy.conf file located at the root of the biogroovy.jar file.  This file should 
	 * never be checked in with user-specific data.
	 * 
	 * @return a ConfigObject with the configuration information.
	 */
	public static ConfigObject getConfig() {

		if(config == null) {
			ConfigSlurper slurper = new ConfigSlurper();

			File file = getConfigFile();
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				// copy the demo file out to the user's directory
				InputStream is = getClass().getResourceAsStream("/biogroovy.conf")
				OutputStream os = new FileOutputStream(file);
				os << is;
				os.flush();
				os.close();

			}

			config = slurper.parse(file.toURI().toURL())

			// if the file has not been customized, throw an exception
			if (config.eutils.email == 'goofy@disney.com') {
				throw new BioGroovyConfigException(msg)
			}
		}
		return config;
	}

	protected static File getConfigFile() {
		Path path = FileSystems.getDefault().getPath(System.getProperty("user.home"), ".biogroovy","biogroovy.conf");
		return path.toFile();
	}

	/**
	 * This method gets the default configuration file and is used for unit testing purposes only.
	 * @return
	 */
	protected static ConfigObject getDefaultConfig() {
		if (config == null) {
			ConfigSlurper slurper = new ConfigSlurper();
			InputStream is = getClass().getResourceAsStream("/biogroovy.conf")
			config = slurper.parse(is)
		}
		return config
	}


}
